package group4.niit;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import group4.niit.JsonParse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.RemoteViews;

public class MyWidget extends AppWidgetProvider {

	private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	private DateFormat timeFormat = new SimpleDateFormat("hh:mm");
	public static final String ACTION_UPDATE = "group4.niit.UPDATE_TIME";
	private ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();
	public static final String API = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=Hanoi+%2C+Vietnam&format=json&num_of_days=5&key=ga6gv8xsnhpcbrkmur5zkz92";
	private Context mContext;
	private JsonParse jsonParse;

	// nhan cac ban tin update cua widget
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.onReceive(context, intent);

		Log.d("UPDATE", "OnReCeive");
		// gọi ra phuong thuc de update khi co lenh ACTION_UPDATE
		if (intent.getAction().equals(ACTION_UPDATE)) {

			Log.d("UPDATE", "OnReCeive: group4.niit.UPDATE_TIME");

			mContext = context;
			AsyntaskGetJson asyntaskGetJson = new AsyntaskGetJson();
			asyntaskGetJson.execute(API);

		}
	}

	// enabled : gui canh bao de update lien tuc theo chu ky

	@Override
	public void onEnabled(Context context) {
		// TODO Auto-generated method stub
		super.onEnabled(context);

		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		calendar.add(Calendar.SECOND, 1);

		Intent intent = new Intent(ACTION_UPDATE);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

		alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
				60000, pendingIntent);
	}

	// huy update khi widget chet
	@Override
	public void onDisabled(Context context) {
		// TODO Auto-generated method stub
		super.onDisabled(context);
		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(ACTION_UPDATE);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

		alarmManager.cancel(pendingIntent);
	}

	//

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// TODO Auto-generated method stub
		super.onUpdate(context, appWidgetManager, appWidgetIds);

		for (int i = 0; i < appWidgetIds.length; i++) {

			updateUIWidget(context, appWidgetManager, appWidgetIds[i]);
		}
	}

	// phuong thuc update giao dien trong widget
	private void updateUIWidget(Context context,
			AppWidgetManager appWidgetManager, int appWidgetId) {
		// lay cac gia tri cua bien de truyen vao
		String date = dateFormat.format(new Date());
		String time = timeFormat.format(new Date());
		String temp_C = "";
		String humidity = "";
		Bitmap icon = null;
		Log.d("UPDATE", "Array size:  " + array.size());
		if (array.size() > 0) {
			humidity = "HUMIDITY:" + array.get(0).get("HUMIDITY") + "%";
			temp_C = "TEMC:" + array.get(0).get("TEMC") + "C";
			/*
			 * temp = "MaxC: " + array.get(0).get("MAXTEM") + " MinC: " +
			 * array.get(0).get("MINTEM");
			 */
			icon = jsonParse.getIconWeather(array.get(0).get("IMAGE"));
		} else {
			humidity = "HUMIDITY: 70" +"%";
			temp_C = "TEMC: 29" +"C";
		}

		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widgetlayout);
		remoteViews.setTextViewText(R.id.humidity, humidity);
		remoteViews.setTextViewText(R.id.date, date);
		remoteViews.setTextViewText(R.id.time, time);
		remoteViews.setTextViewText(R.id.temp, temp_C);

		if (icon != null) {
			remoteViews.setImageViewBitmap(R.id.imgWeather, icon);
		}

		remoteViews.setOnClickPendingIntent(R.id.date, PendingIntent
				.getActivity(context, 0,
						new Intent(context, MultyWidget.class), 0));

		appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

	}

	private class AsyntaskGetJson extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			jsonParse = new JsonParse();
			Log.d("UPDATE", "doInBackground");
			return jsonParse.getStringJson(params[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			getInforWeather(result);
			Log.d("UPDATE", "onPostExecute: Result " + result);
		}
	}

	public void getInforWeather(String result) {
		Log.d("UPDATE", "getInforWeather");
		JSONObject jsonResult = null;
		try {
			jsonResult = new JSONObject(result);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

		Log.d("UPDATE", "getInforWeather: jsonResult is : " + jsonResult);
		if (jsonResult != null) {
			try {
				JSONObject jsonObjectData = jsonResult.getJSONObject("data");
				/*
				 * JSONArray arrayWeather =
				 * jsonObjectData.getJSONArray("weather");
				 */

				JSONArray arrayCC = jsonObjectData
						.getJSONArray("current_condition");

				/* JSONArray wt = jsonObjectData.getJSONArray("weather"); */

				for (int i = 0; i < arrayCC.length(); i++) {

					JSONObject cc = arrayCC.getJSONObject(i);
					HashMap<String, String> hashMap = new HashMap<String, String>();
					hashMap.put("HUMIDITY", cc.getString("humidity"));
					/*hashMap.put("DATE", cc.getString("date"));*/
					hashMap.put("TEMC", cc.getString("temp_C"));
					/*
					 * hashMap.put("MAXTEM", cc.getString("tempMaxC"));
					 * hashMap.put("MINTEM", cc.getString("tempMinC"));
					 */

					JSONArray arrayIcon = cc.getJSONArray("weatherIconUrl");
					String linkIson = arrayIcon.getJSONObject(0).getString(
							"value");
					hashMap.put("IMAGE", linkIson);

					array.add(hashMap);
				}

				/*
				 * for (int i = 0; i < arrayWeather.length(); i++) { JSONObject
				 * object = arrayWeather.getJSONObject(i); HashMap<String,
				 * String> hashMap = new HashMap<String, String>();
				 * 
				 * hashMap.put("DATE", object.getString("date"));
				 * hashMap.put("MAXTEM", object.getString("tempMaxC"));
				 * hashMap.put("MINTEM", object.getString("tempMinC"));
				 * 
				 * JSONArray arrayIcon = object.getJSONArray("weatherIconUrl");
				 * String linkIson = arrayIcon.getJSONObject(0).getString(
				 * "value"); hashMap.put("IMAGE", linkIson);
				 * 
				 * array.add(hashMap); }
				 */

				Log.d("UPDATE", "getInforWeather: Array size : " + array.size());
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		// tu dong update widget k cho he dieu hanh 
		ComponentName componentName = new ComponentName(
				mContext.getPackageName(), getClass().getName());

		AppWidgetManager appWidgetManager = AppWidgetManager
				.getInstance(mContext);
		int[] ids = appWidgetManager.getAppWidgetIds(componentName);

		for (int i = 0; i < ids.length; i++) {
			updateUIWidget(mContext, appWidgetManager, ids[i]);
			Log.d("UPDATE", "Weather: updateUIWidget");
		}

	}

}
